<template>
  <div class="gameA">
    <audio autoplay
      src="https://ziyuan.windbless.top/sounds/lakk/%E5%A4%B8%E8%B5%9E/%E5%B0%8F%E6%9C%8B%E5%8F%8B%E4%BB%AC%EF%BC%8C%E8%AE%A9%E6%88%91%E4%BB%AC%E9%80%89%E6%8B%A9%E5%85%B6%E4%B8%AD%E7%9A%84%E4%B8%80%E5%BC%A0%E6%88%96%E8%80%85%E6%98%AF%E5%A4%9A%E5%BC%A0%E5%9B%BE%E7%89%87%E6%9D%A5%E7%BC%96%E4%B8%80%E4%B8%AA%E5%B0%8F%E6%95%85%E4%BA%8B%E5%90%A7%E3%80%82.mp3"
      ref="finishref" @ended="enddd"></audio>

    <div class="container">
      <div class="detail"> {{ detail }}</div>
      <div class="cards" @click="spreadCards" v-if="topic != null">
        <div @click="chooseone(index)" class="card" v-for="(n, index) in topic.options" :key="n"
          :class="{ spread: isSpread, choose: choose[index] == 1 }">
          <img :src="`${config.Target}${n}`" alt="">
        </div>
      </div>
      <img v-if="choose.includes(1)" src="@/static/record.png" alt="" class="voice" @click="toggleRecording"
        :disabled="isRecording">

    </div>
  </div>
</template>

<script setup>
import config from '@/config/config.js'
import api from '@/api/user.js'
import { ref, onMounted } from 'vue'
import Recorder from 'recorder-core';
const detail = ref("请你选择今天的图片")
const choose = ref([0, 0, 0, 0, 0, 0]);
import { message } from 'ant-design-vue';
import 'recorder-core/src/engine/mp3';
import 'recorder-core/src/engine/mp3-engine';
//录制wav格式的用这一句就行
import 'recorder-core/src/engine/wav';
//可选的插件支持项，这个是波形可视化插件
import 'recorder-core/src/extensions/waveview';
import { useRouter } from 'vue-router';
//ts import 提示：npm包内已自带了.d.ts声明文件（不过是any类型）
const finishref = ref(null);
const router = useRouter();
const isRecording = ref(false);
let rec;
let recBlob;
let wave;
const id = ref();
const recwave = ref(null);
const topic = ref(null);
onMounted(() => {
  const iframe = document.getElementById("iframe");
  if (iframe) {
    iframe.parentNode.removeChild(iframe);
  }
  recOpen();
  getTellStory();
})
const chooseone = (n) => {
  if (isSpread.value) {

    if (choose.value[n] == 1) {
      choose.value[n] = 2
    } else {
      choose.value[n] = 1
    }
  }
  console.log(choose.value.indexOf(1));
}
const isSpread = ref(false);

const spreadCards = () => {
  if (!isSpread.value) {
    isSpread.value = !isSpread.value;
    detail.value = "点击下方卡片选择图片"
  }

};
const toggleRecording = () => {
  if (!isRecording.value) {
    isRecording.value = 1;
    message.success('开始录音');
    recStart()
  } else {
    recStop();
    message.success('结束录音');
  }
};
function recOpen() {
  //创建录音对象
  rec = Recorder({
    type: 'mp3', //录音格式，可以换成wav等其他格式
    sampleRate: 16000, //录音的采样率，越大细节越丰富越细腻
    bitRate: 16, //录音的比特率，越大音质越好
    onProcess: (
      buffers,
      powerLevel,
      bufferDuration,
      bufferSampleRate,
      newBufferIdx,
      asyncEnd,
    ) => {
      //录音实时回调，大约1秒调用12次本回调
      //可实时绘制波形，实时上传（发送）数据
      if (wave) {
        wave.input(buffers[buffers.length - 1], powerLevel, bufferSampleRate);
      }
    },
  });
  if (!rec) {
    alert('当前浏览器不支持录音功能！');
    return;
  }
  rec.open(
    () => {
      console.log('录音已打开');
      if (recwave.value) {
        //创建音频可视化图形绘制对象
        wave = Recorder.WaveView({ elem: recwave.value });
      }
    },
    (msg, isUserNotAllow) => {
      //用户拒绝了录音权限，或者浏览器不支持录音
    },
  );

}
function recStart() {
  if (!rec) {
    console.error('未打开录音');
    return;
  }
  rec.start();
  console.log('已开始录音');
}
function recStop() {
  if (!rec) {
    console.error('未打开录音');
    return;
  }
  rec.stop(
    (blob, duration) => {
      //blob就是我们要的录音文件对象，可以上传，或者本地播放
      recBlob = blob;
      //简单利用URL生成本地文件地址，此地址只能本地使用，比如赋值给audio.src进行播放，赋值给a.href然后a.click()进行下载（a需提供download="xxx.mp3"属性）
      const localUrl = (window.URL || window.webkitURL).createObjectURL(blob);
      console.log('录音成功', blob, localUrl, '时长:' + duration + 'ms');
      upload(blob);
      rec.close(); //关闭录音，释放录音资源，当然可以不释放，后面可以连续调用start
      rec = null;
      // recPlay();
    },
    (err) => {
      console.error('结束录音出错：' + err);
      rec.close(); //关闭录音，释放录音资源，当然可以不释放，后面可以连续调用start
      rec = null;
    },
  );
}
const upload = (blob) => {
  const formData = new FormData();
  formData.append('file', blob, "recording.mp3"); // 'recording.wav' 是文件名，可以根据实际情况修改
  api.updatefile(formData).then((res) => {
    const selectedOptions = choose.value
      .map((value, index) => value === 1 ? topic.value.options[index] : null)
      .filter(option => option !== null);

    // 将选项数组拼接成一个逗号分隔的字符串
    const userAnswer = selectedOptions.join(',');
    console.log(userAnswer);
    
    api.putUserProgress({
      "id": id.value,
      "useranswer": userAnswer,
      "userrecordingfile": res.url,
      "rewardobtained": "0coin"
    }).then((res) => {
      console.log(res);
      router.push('/game5finish')
    })
  })

}
const getTellStory = async () => {
  const res = await api.getTellStory();
  if (res.code == 200) {
    console.log(res.data);
    findbyid(res.data.questionnumber)
    id.value = res.data.id
    // topic.value = res.data;
    // detail.value = res.data.questiontext
  } else {
    let res = await api.getquestion1({
      creationtime: getCurrentFormattedDate()
    })
    id.value = res.rows[3].id
    findbyid(res.rows[3].questionnumber)
  }

}
function getCurrentFormattedDate() {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;
}
async function findbyid(id) {

  const resitem = await api.getonelist({
    questionnumber: id
  });
  console.log(resitem.rows[0]);
  topic.value = resitem.rows[0];
  topic.value.options = topic.value.options.split(',')
  topic.value.options.length = 3;
  detail.value = resitem.rows[0].questiontext

}
</script>

<style lang="scss" scoped>
.gameA {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-image: url('@/static/processback.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  gap: 2rem;

  .container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 80%;
    height: 80%;
    background-color: antiquewhite;
    border-radius: 2rem;
    gap: 3rem;

    .detail {
      font-size: 3rem;
    }

    .voice {

      height: 8rem;
      width: 8rem;
    }
  }

  .cards {
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    width: 80%;
    height: 80%;
  }

  .card {
    position: absolute;
    width: 12rem;
    height: 12rem;
    background-color: white;
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: all 0.5s ease;
    transform: scale(1);
    padding: 1rem !important;

    img {
      width: 100%;
    }
  }

  .card.spread {
    transform: scale(1.2);
  }

  .card.lose {
    display: none;
  }

  .card.choose {
    background-color: aquamarine;
  }

  .card:nth-child(1) {
    top: 0;
    left: 0;
  }

  .card:nth-child(2) {
    top: 0;
    left: 2rem;
  }

  .card:nth-child(3) {
    top: 0;
    left: 4rem;
  }

  .card:nth-child(4) {
    top: 0;
    left: 6rem;
  }

  .card:nth-child(5) {
    top: 0;
    left: 8rem;
  }

  .card:nth-child(6) {
    top: 0;
    left: 10rem;
  }

  .card:nth-child(7) {
    top: 0;
    left: 12rem;
  }

  .card:nth-child(8) {
    top: 0;
    left: 14rem;
  }

  .card:nth-child(9) {
    top: 0;
    left: 16rem;
  }

  .card:nth-child(10) {
    top: 0;
    left: 18rem;
  }

  .card.spread:nth-child(1) {
    top: 0;
    left: 0;
  }

  .card.spread:nth-child(2) {
    top: 0;
    left: 15rem;
  }

  .card.spread:nth-child(3) {
    top: 0;
    left: 30rem;
  }

  .card.spread:nth-child(4) {
    top: 0;
    left: 45rem;
  }

  .card.spread:nth-child(5) {
    top: 15rem;
    left: 0;
  }

  .card.spread:nth-child(6) {
    top: 12rem;
    left: 12rem;
  }

  .card.spread:nth-child(7) {
    top: 12rem;
    left: 24rem;
  }

  .card.spread:nth-child(8) {
    top: 12rem;
    left: 36rem;
  }

  .card.spread:nth-child(9) {
    top: 24rem;
    left: 12rem;
  }

  .card.spread:nth-child(10) {
    top: 24rem;
    left: 24rem;
  }

}
</style>